// Copyright Epic Games, Inc. All Rights Reserved.

#include "httpmulti.h"

#include <zencore/logging.h>

#if ZEN_PLATFORM_WINDOWS
#	include <conio.h>
#endif

namespace zen {

HttpMultiServer::HttpMultiServer()
{
}

HttpMultiServer::~HttpMultiServer()
{
}

void
HttpMultiServer::RegisterService(HttpService& Service)
{
	for (auto& Server : m_Servers)
	{
		Server->RegisterService(Service);
	}
}

int
HttpMultiServer::Initialize(int BasePort, std::filesystem::path DataDir)
{
	ZEN_UNUSED(DataDir);
	ZEN_ASSERT(!m_IsInitialized);

	int EffectivePort = 0;

	for (auto& Server : m_Servers)
	{
		const int InitializeResult = Server->Initialize(BasePort, DataDir);

		if (!EffectivePort)
		{
			EffectivePort = InitializeResult;
		}
	}

	m_IsInitialized = true;

	return EffectivePort;
}

void
HttpMultiServer::Run(bool IsInteractiveSession)
{
	const bool TestMode = !IsInteractiveSession;

	int WaitTimeout = -1;
	if (!TestMode)
	{
		WaitTimeout = 1000;
	}

#if ZEN_PLATFORM_WINDOWS
	if (TestMode == false)
	{
		ZEN_CONSOLE("Zen Server running (multi server). Press ESC or Q to quit");
	}

	do
	{
		if (!TestMode && _kbhit() != 0)
		{
			char c = (char)_getch();

			if (c == 27 || c == 'Q' || c == 'q')
			{
				RequestApplicationExit(0);
			}
		}

		m_ShutdownEvent.Wait(WaitTimeout);
	} while (!IsApplicationExitRequested());
#else
	if (TestMode == false)
	{
		ZEN_CONSOLE("Zen Server running (null HTTP). Ctrl-C to quit");
	}

	do
	{
		m_ShutdownEvent.Wait(WaitTimeout);
	} while (!IsApplicationExitRequested());
#endif
}

void
HttpMultiServer::RequestExit()
{
	m_ShutdownEvent.Set();
}

void
HttpMultiServer::Close()
{
}

void
HttpMultiServer::AddServer(Ref<HttpServer> Server)
{
	ZEN_ASSERT(!m_IsInitialized);

	m_Servers.push_back(std::move(Server));
}

}  // namespace zen
